package com.ssm.server.user.service.impl;

import com.ssm.server.boxes.dao.BoxDao;
import com.ssm.server.boxes.dao.BoxesDao;
import com.ssm.server.boxes.dao.ClassesDao;
import com.ssm.server.boxes.model.Box;
import com.ssm.server.boxes.model.Boxes;
import com.ssm.server.boxes.model.Classes;
import com.ssm.server.boxes.model.GiveBox;
import com.ssm.server.common.JsonData;
import com.ssm.server.consts.CmsConstants;
import com.ssm.server.consts.CodeEnum;
import com.ssm.server.consts.SysParamEnum;
import com.ssm.server.consts.WXPayConstants;
import com.ssm.server.consts.WXPayConstants.SignType;
import com.ssm.server.sysparam.dao.SysMessageDao;
import com.ssm.server.sysparam.dao.SysNewsDao;
import com.ssm.server.sysparam.dao.SysParamDao;
import com.ssm.server.sysparam.model.SysMessage;
import com.ssm.server.sysparam.model.SysNews;
import com.ssm.server.sysparam.model.SysParam;
import com.ssm.server.user.dao.GteTicketLogDao;
import com.ssm.server.user.dao.OrderDao;
import com.ssm.server.user.dao.PayLogDao;
import com.ssm.server.user.dao.PayRecordDao;
import com.ssm.server.user.dao.PrizeBagDao;
import com.ssm.server.user.dao.PrizeCoinLogDao;
import com.ssm.server.user.dao.PrizeLogDao;
import com.ssm.server.user.dao.PrizeTicketDao;
import com.ssm.server.user.dao.PrizeTicketManageDao;
import com.ssm.server.user.dao.UnreadNewsDao;
import com.ssm.server.user.dao.UserCoinDao;
import com.ssm.server.user.dao.UserDao;
import com.ssm.server.user.dao.VoucherCenterDao;
import com.ssm.server.user.model.GetTicketLog;
import com.ssm.server.user.model.Order;
import com.ssm.server.user.model.PayLog;
import com.ssm.server.user.model.PayRecord;
import com.ssm.server.user.model.PrizeBag;
import com.ssm.server.user.model.PrizeCoinLog;
import com.ssm.server.user.model.PrizeLog;
import com.ssm.server.user.model.PrizeTicket;
import com.ssm.server.user.model.PrizeTicketManage;
import com.ssm.server.user.model.UnreadNews;
import com.ssm.server.user.model.User;
import com.ssm.server.user.model.UserCoin;
import com.ssm.server.user.model.VoucherCenter;
import com.ssm.server.user.service.UserService;
import com.ssm.server.util.CertHttpUtil;
import com.ssm.server.util.DateUtil;
import com.ssm.server.util.HttpUtil;
import com.ssm.server.util.JsonUtil;
import com.ssm.server.util.RedisUtil;
import com.ssm.server.util.StringUtil;
import com.ssm.server.util.TokenUse;
import com.ssm.server.util.WXPayUtil;
import com.ssm.server.util.WechatDecryptDataUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.ssm.server.boxes.dao.GiveBoxDao;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangyibo
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
	private static final Logger LOGGER = Logger.getLogger(User.class);
	@Autowired
	private UserDao userDao;
	@Autowired
	private PrizeBagDao prizeBagDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private PrizeLogDao prizeLogDao;
	@Autowired
	private PrizeTicketDao prizeTicketDao;
	@Autowired
	private VoucherCenterDao voucherCenterDao;
	@Autowired
	private PrizeTicketManageDao prizeTicketManageDao;
	@Autowired
	private ClassesDao classesDao;

	@Autowired
	private PayRecordDao payRecordDao;
	@Autowired
	private BoxDao boxDao;
	@Autowired
	private BoxesDao boxesDao;
	@Autowired
	private SysParamDao sysParamDao;
	@Autowired
	private SysMessageDao sysMessageDao;

	@Autowired
	private GiveBoxDao giveBoxDao;

	@Autowired
	private PayLogDao payLogDao;

	@Autowired
	private SysNewsDao sysNewsDao;
	@Autowired
	private UnreadNewsDao unreadNewsDao;

	@Autowired
	private UserCoinDao userCoinDao;

	@Autowired
	private PrizeCoinLogDao prizeCoinLogDao;

	@Autowired
	private GteTicketLogDao getTicketLogDao;

	@Override
	public JsonData getPrizeBag(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String typeId = maps.get("typeId").toString();// 状态 1为预售 ,2为现货
															// ,3为售罄（不显示） 4为是否限定
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		int page = Integer.valueOf(param.get("page"));
		int limit = Integer.valueOf(param.get("limit"));
		try {
			int countSize = limit;
			int pageCount = (page - 1) * countSize;
			List<PrizeBag> prizeBag = prizeBagDao.getPrizeBag(TokenUse.getUserID(token), Integer.valueOf(typeId),
					countSize, pageCount);
			jsonData.setData(prizeBag);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getOrderByUser(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String month = maps.get("month").toString();
		String year = maps.get("year").toString();
		String token = param.get("token");
		try {

			List<Order> order = orderDao.getOrderByUser(TokenUse.getUserID(token), year, month);
			for (int i = 0; i < order.size(); i++) {
				List<PrizeBag> prizeBag = prizeBagDao.getPrizeBagByOrderNumber(order.get(i).getOrderNumber());
				order.get(i).setPirzeBag(prizeBag);
			}
			jsonData.setData(order);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getPrizeLog(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String boxesId = maps.get("boxesId").toString();
		JsonData jsonData = new JsonData();
		try {
			List<PrizeLog> prizeLog = prizeLogDao.getPrizeLog(Integer.valueOf(boxesId));
			jsonData.setData(prizeLog);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getPrizeTicketByUser(Map<String, String> param) throws Exception {
		String token = param.get("token").toString();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String state = maps.get("state").toString();
		int page = Integer.valueOf(param.get("page"));
		int limit = Integer.valueOf(param.get("limit"));
		JsonData jsonData = new JsonData();
		try {
			int countSize = limit;
			int pageCount = (page - 1) * countSize;
			List<PrizeTicket> prizeTicket = prizeTicketDao.getPrizeTicketByUsers(Integer.valueOf(state),
					TokenUse.getUserID(token), countSize, pageCount);
			for (int i = 0; i < prizeTicket.size(); i++) {
				Date date = new Date();
				// 赏票过期state改为2
				if (prizeTicket.get(i).getValidTime().before(date)) {
					prizeTicketDao.updatePrizeTicketState(prizeTicket.get(i).getTicketId());
				}
			}
			jsonData.setData(prizeTicket);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getUserById(Map<String, String> param) throws Exception {
		String token = param.get("token");
		JsonData jsonData = new JsonData();
		try {
			User user = userDao.getUserById(TokenUse.getUserID(token));

			List<PrizeTicket> prizeTicket = prizeTicketDao.getPrizeTicketByUser(user.getUserId());
			int size = prizeTicket.size();
			user.setPrizeTicketSize(size);
			jsonData.setData(user);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getVoucherCenter(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		try {
			List<VoucherCenter> voucherCenter = voucherCenterDao.getVoucherCenter();
			jsonData.setData(voucherCenter);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);

		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData updateaUserPrizeCoin(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String ticketId = maps.get("ticketId").toString();
		String token = param.get("token");
		JsonData jsonData = new JsonData();
		try {
			PrizeTicket prizeTicket = prizeTicketDao.getPrizeTicketById(Integer.valueOf(ticketId));
			if (prizeTicket.getState() == 1) {
				User use = userDao.getUserById(TokenUse.getUserID(token));
				BigDecimal peizeCoin = use.getPrizeCoin();
				User users = new User();
				users.setUserId(TokenUse.getUserID(token));

				PrizeTicket classesId = prizeTicketDao.getPrizeTicketById(Integer.valueOf(ticketId));

				float max = 0;
				float min = 0;
				if (classesId.getClassesId() == 0) {
					SysParam sysParam = sysParamDao.findSysParamByKey(SysParamEnum.SYSRANDOMNUMBER.getName());
					max = Float.valueOf(sysParam.getValue());
					min = 2;
				} else {
					Classes classes = classesDao.getClassesById(classesId.getClassesId());
					max = classes.getPrizeCoinBig();
					min = classes.getPrizeCoinSmall();
				}

				BigDecimal ispeizeCoinRand = new BigDecimal(Math.random() * (max - min) + min);
				BigDecimal peizeCoinRand = ispeizeCoinRand.setScale(1, BigDecimal.ROUND_HALF_UP);
				System.out.println("随机获得赏币数=================" + peizeCoinRand);
				users.setPrizeCoin(peizeCoinRand.add(peizeCoin));
				userDao.updateaUserPrizeCoin(users);
				jsonData.setData(peizeCoinRand);
				prizeTicketDao.updatePrizeTicketState(prizeTicket.getTicketId());

				// 赏票获取记录
				UserCoin userCoin = new UserCoin();
				userCoin.setCoinNumber(peizeCoinRand);
				userCoin.setUserId(TokenUse.getUserID(token));
				userCoinDao.saveUserCoin(userCoin);
			}

			jsonData.setCodeEnum(CodeEnum.SUCCESS);

		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData buyBox(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		JsonData jsonData = new JsonData();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String type = maps.get("type").toString();// 抽奖类型 1抽一发 2抽三发 3抽五发 4为全收
		String boxesId = maps.get("boxesId").toString();
		String isPrizeCoin = maps.get("isPrizeCoin").toString();// 是否使用赏币0为不用
		String token = param.get("token");
		String outtradeno = WXPayUtil.getOrderId();// 生成订单号
		User users = userDao.getUserById(TokenUse.getUserID(token));
		BigDecimal prizeCoins = users.getPrizeCoin();

		Boxes boxes = boxesDao.getBoxes(Integer.valueOf(boxesId));
		Classes classes = classesDao.getClassesById(Integer.valueOf(boxes.getClassesId()));
		BigDecimal price = classes.getPrice();
		BigDecimal money = new BigDecimal(0);
		BigDecimal prizeCoin = new BigDecimal(0);

		int howDraw = 0;

		int ruleId = classes.getRuleId();
		StringBuffer boxIds = new StringBuffer();
		int boxCount = boxDao.boxesSumboxNow(Integer.valueOf(boxesId));
		if (Integer.valueOf(type) == 1) { // 1抽一发
			howDraw = 1;
		}
		if (Integer.valueOf(type) == 2) {// 1抽三发
			howDraw = 3;
		}
		if (Integer.valueOf(type) == 3) {
			howDraw = 5;
		}
		if (Integer.valueOf(type) == 4) {
			int count = boxDao.boxesSumboxNow(boxes.getBoxesId());
			howDraw = count;
		}
		if (boxCount == 0 || howDraw > boxCount) {
			jsonData.setCodeEnum(CodeEnum.BOXERROR);
			return jsonData;
		}

		BigDecimal howDrawCount = new BigDecimal(howDraw);// 来几发
		money = price.multiply(howDrawCount);
		if (Integer.valueOf(isPrizeCoin) == 1) {// 是否使用赏币
			if (money.compareTo(prizeCoins) > -1) { // 金额大于等于用户赏币
				money = money.subtract(prizeCoins);
			} else {
				jsonData.setData("跳转余额支付");
				jsonData.setCodeEnum(CodeEnum.SUCCESS);
				return jsonData;
			}
		}

		List<Box> box = boxDao.getLastBoxAll(Integer.valueOf(boxesId));
		int sumCount = boxDao.boxesSumboxNow(Integer.valueOf(boxesId));
		int SumCountAll = boxDao.boxesSumbox(Integer.valueOf(boxesId));
		int residueCount = SumCountAll - sumCount;
		if (ruleId == 1) {
			wai: for (int i = 0; i < howDraw; i++) {
				Random random = new Random();
				List<Integer> boxIdList = new ArrayList<Integer>();
				for (Box boxs : box) {
					for (int j = 0; j < boxs.getBoxNowSum(); j++) {
						boxIdList.add(boxs.getBoxId());
					}
				}
				int winNumber = random.nextInt(boxIdList.size());
				// boolean ifTrue = RedisUtil.exists("manghe" +
				// boxIdList.get(winNumber));
				// if (ifTrue) {
				// String countNumber = RedisUtil.get("manghe" +
				// boxIdList.get(winNumber));

				nei: for (int p = 0; p < box.size(); p++) {
					if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
						// nowSum = box.get(p).getBoxNowSum() -
						// Integer.valueOf(countNumber);
						box.get(p).setBoxNowSum(box.get(p).getBoxNowSum() - 1);
						if (box.get(p).getBoxNowSum() < 0) {
							box.remove(p);
							if (box.size() <= 0) {
								jsonData.setCodeEnum(CodeEnum.BOXERROR);
								return jsonData;
							} else {
								i--;
								continue wai;
							}
						} else {
							// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
							// - 1);
							if (boxIds.length() == 0) {
								boxIds = new StringBuffer();
								boxIds.append(boxIdList.get(winNumber));
							} else {
								boxIds.append("," + boxIdList.get(winNumber));
							}
							// RedisUtil.incr("manghe" +
							// boxIdList.get(winNumber));
						}
						break nei;
					}
				}
				// } else {
				// //
				// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
				// // - 1);
				// if (StringUtil.isEmpty(boxIds)) {
				// boxIds = boxIdList.get(winNumber) + "";
				// } else {
				// boxIds = boxIds + "," + boxIdList.get(winNumber);
				// }
				// RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1",
				// 60);
				// }
			}
		} else if (ruleId == 2) {
			wai: for (int i = 0; i < howDraw; i++) {
				Random random = new Random();
				List<Integer> boxIdList = new ArrayList<Integer>();
				for (Box boxs : box) {
					for (int j = 0; j < boxs.getBoxNowSum(); j++) {
						boxIdList.add(boxs.getBoxId());
					}
				}
				int winNumber = random.nextInt(boxIdList.size());
				// boolean ifTrue = RedisUtil.exists("manghe" +
				// boxIdList.get(winNumber));
				// if (ifTrue) {
				// String countNumber = RedisUtil.get("manghe" +
				// boxIdList.get(winNumber));
				nei: for (int p = 0; p < box.size(); p++) {
					if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
						// nowSum = box.get(p).getBoxNowSum() -
						// Integer.valueOf(countNumber);
						box.get(p).setBoxNowSum(box.get(p).getBoxNowSum() - 1);
						if (box.get(p).getBoxNowSum() < 0) {
							box.remove(p);
							if (box.size() <= 0) {
								jsonData.setCodeEnum(CodeEnum.BOXERROR);
								return jsonData;
							} else {
								i--;
								continue wai;
							}
						} else {
							// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
							// - 1);
							if (boxIds.length() == 0) {
								boxIds = new StringBuffer();
								boxIds.append(boxIdList.get(winNumber));
							} else {
								boxIds.append("," + boxIdList.get(winNumber));
							}
							// RedisUtil.incr("manghe" +
							// boxIdList.get(winNumber));
							residueCount = residueCount + 1;
						}
						break nei;
					}
				}
				// } else {
				// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
				// - 1);
				// if (StringUtil.isEmpty(boxIds)) {
				// boxIds = boxIdList.get(winNumber)+ "";
				// } else {
				// boxIds = boxIds + "," + boxIdList.get(winNumber);
				// }
				// RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1",
				// 60);
			}
			if (SumCountAll == residueCount) {
				Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
				boxIds.append("," + lastBox.getBoxId());

			}
			// }
		} else if (ruleId == 3) {
			GiveBox giveBox = new GiveBox();
			wai: for (int i = 0; i < howDraw; i++) {
				Random random = new Random();
				List<Integer> boxIdList = new ArrayList<Integer>();
				for (Box boxs : box) {
					for (int j = 0; j < boxs.getBoxNowSum(); j++) {
						boxIdList.add(boxs.getBoxId());
					}
				}
				int winNumber = random.nextInt(boxIdList.size());
				// boolean ifTrue = RedisUtil.exists("manghe" +
				// boxIdList.get(winNumber));
				// if (ifTrue) {
				// String countNumber = RedisUtil.get("manghe" +
				// boxIdList.get(winNumber));
				nei: for (int p = 0; p < box.size(); p++) {
					if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
						// nowSum = box.get(p).getBoxNowSum() -
						// Integer.valueOf(countNumber);
						box.get(p).setBoxNowSum(box.get(p).getBoxNowSum() - 1);
						if (box.get(p).getBoxNowSum() < 0) {
							box.remove(p);
							if (box.size() <= 0) {
								jsonData.setCodeEnum(CodeEnum.BOXERROR);
								return jsonData;
							} else {
								i--;
								continue wai;
							}
						} else {
							// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
							// - 1);
							if (boxIds.length() == 0) {
								boxIds = new StringBuffer();
								boxIds.append(boxIdList.get(winNumber));
							} else {
								boxIds.append("," + boxIdList.get(winNumber));
							}
							// RedisUtil.incr("manghe" +
							// boxIdList.get(winNumber));
							residueCount = residueCount + 1;
						}
						break nei;
					}
				}
				// } else {
				// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
				// - 1);
				// if (StringUtil.isEmpty(boxIds)) {
				// boxIds = boxIdList.get(winNumber) + "";
				// } else {
				// boxIds = boxIds + "," + boxIdList.get(winNumber);
				// }
				// RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1",
				// 60);
				// }
				int ceaseCount = (int) Math.ceil(Double.valueOf(SumCountAll) / 2.0);
				if (residueCount == ceaseCount) {
					Box boxFrist = boxDao.getboxByFrist(Integer.valueOf(boxesId));
					giveBox.setBoxId(boxFrist.getBoxId());
					giveBox.setUserId(users.getUserId());
					giveBox.setBoxLevel(Integer.valueOf(boxFrist.getBoxLevel()));
					giveBox.setOrderNumber(outtradeno);
					giveBoxDao.saveGiveBoxByBoxId(giveBox);
				} else if (SumCountAll == residueCount) {
					Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
					boxIds.append("," + lastBox.getBoxId());
				}
			}
		} else if (ruleId == 4) {
			GiveBox giveBox = new GiveBox();
			GiveBox giveWLsetBox = new GiveBox();
			wai: for (int i = 0; i < howDraw; i++) {
				Random random = new Random();
				List<Integer> boxIdList = new ArrayList<Integer>();
				for (Box boxs : box) {
					for (int j = 0; j < boxs.getBoxNowSum(); j++) {
						boxIdList.add(boxs.getBoxId());
					}
				}
				int winNumber = random.nextInt(boxIdList.size());
				// boolean ifTrue = RedisUtil.exists("manghe" +
				// boxIdList.get(winNumber));
				// if (ifTrue) {
				// String countNumber = RedisUtil.get("manghe" +
				// boxIdList.get(winNumber));
				nei: for (int p = 0; p < box.size(); p++) {
					if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
						box.get(p).setBoxNowSum(box.get(p).getBoxNowSum() - 1);
						if (box.get(p).getBoxNowSum() < 0) {
							box.remove(p);
							if (box.size() <= 0) {
								jsonData.setCodeEnum(CodeEnum.BOXERROR);
								return jsonData;
							} else {
								i--;
								continue wai;
							}
						} else {
							// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
							// - 1);
							if (boxIds.length() == 0) {
								boxIds = new StringBuffer();
								boxIds.append(boxIdList.get(winNumber));
							} else {
								boxIds.append("," + boxIdList.get(winNumber));
							}
							// RedisUtil.incr("manghe" +
							// boxIdList.get(winNumber));
							residueCount = residueCount + 1;
						}
						break nei;
					}
				}
				// }
				// int nowSum = box.get(winNumber).getBoxNowSum() -
				// Integer.valueOf(countNumber);
				// if (nowSum <= 0) {
				// box.remove(winNumber);
				// if (box.size() <= 0) {
				// jsonData.setCodeEnum(CodeEnum.BOXERROR);
				// return jsonData;
				// } else {
				// i--;
				// continue;
				// }
				// } else {
				// //
				// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
				// // - 1);
				// if (StringUtil.isEmpty(boxIds)) {
				// boxIds = boxIdList.get(winNumber) + "";
				// } else {
				// boxIds = boxIds + "," + boxIdList.get(winNumber);
				// }
				// RedisUtil.incr("manghe" + box.get(winNumber).getBoxId());
				// residueCount = residueCount + 1;
				// }
				// } else {
				// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
				// - 1);
				// if (StringUtil.isEmpty(boxIds)) {
				// boxIds = boxIdList.get(winNumber) + "";
				// } else {
				// boxIds = boxIds + "," + boxIdList.get(winNumber);
				// }
				// RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1",
				// 60);
				// residueCount = residueCount + 1;
				// }
				// residueCount = residueCount + 1;
				int ceaseCount = (int) Math.ceil(Double.valueOf(SumCountAll) / 2.0);
				if (residueCount == ceaseCount) {

					Box boxFrist = boxDao.getboxByFrist(Integer.valueOf(boxesId));
					giveBox.setBoxId(boxFrist.getBoxId());
					giveBox.setUserId(users.getUserId());
					giveBox.setBoxLevel(Integer.valueOf(boxFrist.getBoxLevel()));
					giveBox.setOrderNumber(outtradeno);
					giveBoxDao.saveGiveBoxByBoxId(giveBox);
				} else if (SumCountAll == residueCount) {

					Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
					boxIds.append("," + lastBox.getBoxId());

					Box boxW = boxDao.getboxByW(Integer.valueOf(boxesId));
					giveWLsetBox.setBoxId(boxW.getBoxId());
					giveWLsetBox.setUserId(users.getUserId());
					giveWLsetBox.setBoxLevel(Integer.valueOf(boxW.getBoxLevel()));
					giveWLsetBox.setOrderNumber(outtradeno);
					giveBoxDao.saveGiveBoxByBoxId(giveWLsetBox);
				}
			}
		}
		String[] cardNumber = String.valueOf(boxIds).split(",");
		if (howDraw > cardNumber.length) {
			jsonData.setCodeEnum(CodeEnum.BOXERROR);
			return jsonData;
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("trade_type", "JSAPI");// 交易類型
		map.put("openid", users.getOpenId());// 扫码人的openid(公众号支付必传)
		map.put("appid", CmsConstants.WEIXIN_MINI_APPID);// 公眾賬號id
		map.put("mch_id", CmsConstants.WEIXIN_SHOPNUMBER);// 商戶號
		map.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
		map.put("body", "11111");// 订单描述
		map.put("out_trade_no", outtradeno);// 商户订单号
		map.put("total_fee", WXPayUtil.getMoney(money + ""));// 标价金额（分为单位）
		map.put("spbill_create_ip", WXPayUtil.getIp(request));// 客户端ip
		// System.out.println("客户端ip:"+WeiXinUtil.getIp(this.getRequest()));
		map.put("notify_url", CmsConstants.WEIXIN_URL + "/blind_box_mall/security/paySuccess");// 支付成功回調地址,通知url必须为外网可访问的url,不能携带参数。
		String sign = WXPayUtil.generateSignature(map, CmsConstants.WEIXIN_KEY, SignType.MD5);
		map.put("sign", sign);// 签名
		// 轉成XML
		String xml = WXPayUtil.mapToXml(map);
		// 發起post請求
		String response = HttpUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
		System.out.println("1---" + response);
		// xml 转 map
		Map<String, String> resData = WXPayUtil.xmlToMap(response);
		if (resData.get("return_code").equals("FAIL")) {
			jsonData.setCodeEnum(CodeEnum.ERROR_PAY);
			jsonData.setMsg(resData.get("return_msg"));
			return jsonData;
		} else if (resData.get("result_code").equals("FAIL")) {
			jsonData.setCodeEnum(CodeEnum.ERROR_PAY);
			jsonData.setMsg(resData.get("err_code_des"));
			return jsonData;
		}
		PayRecord payRecord = new PayRecord();
		payRecord.setUserId(users.getUserId());
		payRecord.setMoney(money);
		payRecord.setOrderNumber(outtradeno);
		payRecord.setBoxId(String.valueOf(boxIds));
		payRecord.setState(0);
		payRecord.setPrizeCoin(prizeCoin);
		payRecord.setPrizeCoins(users.getPrizeCoin());
		payRecord.setIsPrizeCoin(Integer.valueOf(isPrizeCoin));
		payRecordDao.savePayRecord(payRecord);
		Map<String, String> returnMap = new HashMap<String, String>();
		returnMap.put("appId", CmsConstants.WEIXIN_MINI_APPID);
		String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
		returnMap.put("timeStamp", timeStamp);
		returnMap.put("nonceStr", WXPayUtil.generateNonceStr());
		returnMap.put("package", "prepay_id=" + resData.get("prepay_id"));
		returnMap.put("signType", "MD5");
		String paySign = WXPayUtil.generateSignature(returnMap, CmsConstants.WEIXIN_KEY, SignType.MD5);
		System.out.println(paySign);
		returnMap.put("paySign", paySign);// 签名
		returnMap.put("outtradeno", outtradeno);
		jsonData.setData(returnMap);
		jsonData.setCodeEnum(CodeEnum.SUCCESS);
		return jsonData;

	}

	@Override
	public JsonData payCallBackHandle(Map<String, String> param) throws Exception {
		JsonData jsonUser = new JsonData();
		String inputLine;
		String notityXml = "";
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			if (StringUtils.isEmpty(notityXml)) {
				System.out.println("支付回调xml为空");
			} else {
				// xml转map
				Map<String, String> resData = WXPayUtil.xmlToMap(notityXml);
				System.out.println(resData);
				if (resData.get("return_code").equals("SUCCESS")) {
					if (resData.get("result_code").equals("SUCCESS")) {
						PayRecord payRecord = payRecordDao
								.getPayRecordByOrderNumber(resData.get("out_trade_no").toString());
						if (payRecord.getState() == 0) {
							// 判断库存
							String[] boxId = payRecord.getBoxId().split(",");
							all: for (int j = 0; j < boxId.length; j++) {

								Box boxSum = boxDao.getboxByBoxId(Integer.valueOf(boxId[j]));
								if (boxSum.getBoxNowSum() - 1 < 0) {
									payRecord.setState(2);
									break all;
								}
							}
							if (payRecord.getState() == 2) {
								payRecordDao.updatePayRecord(payRecord);
								Map<String, String> map = new HashMap<String, String>();
								map.put("appid", CmsConstants.WEIXIN_MINI_APPID);// 公眾賬號id
								map.put("mch_id", CmsConstants.WEIXIN_SHOPNUMBER);// 商戶號
								map.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
								map.put("out_trade_no", payRecord.getOrderNumber());// 商户订单号
								map.put("out_refund_no", WXPayUtil.generateNonceStr() + payRecord.getOrderNumber());// 商户订单号
								map.put("total_fee", WXPayUtil.getMoney(payRecord.getMoney() + ""));// 标价金额（分为单位）
								map.put("refund_fee", WXPayUtil.getMoney(payRecord.getMoney() + ""));
								// System.out.println("客户端ip:"+WeiXinUtil.getIp(this.getRequest()));
								String sign = WXPayUtil.generateSignature(map, CmsConstants.WEIXIN_KEY, SignType.MD5);
								map.put("sign", sign);// 签名
								// 轉成XML
								String xml = WXPayUtil.mapToXml(map);
								// 發起post請求
								String response = CertHttpUtil
										.postData("https://api.mch.weixin.qq.com/secapi/pay/refund", xml);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
								System.out.println(
										"退款返回结果++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + response);
							} else {
								payRecord.setState(1);
								payRecordDao.updatePayRecord(payRecord);
								int thisboxid = 0;
								String[] boxIds = payRecord.getBoxId().split(",");
								thisboxid = Integer.valueOf(boxIds[0]);
								for (int j = 0; j < boxIds.length; j++) {
									// 减库存
									boxDao.updateBoxFristNowNumber(Integer.valueOf(boxIds[j]));
									// 获奖记录
									PrizeLog prizeLog = new PrizeLog();
									prizeLog.setUserId(payRecord.getUserId());
									prizeLog.setBoxId(Integer.valueOf(boxIds[j]));
									prizeLogDao.savePrizeLog(prizeLog);

									Boxes boxes = boxesDao.getBoxesById(Integer.valueOf(boxIds[j]));
									Classes classes = classesDao.getClassesById(Integer.valueOf(boxes.getClassesId()));

									// 用户赠送赏票
									if (classes.getIsPrizeTicket() == 1) {
										PrizeTicket prizeTicket = new PrizeTicket();
										Date dates = new Date();
										Date newDate = DateUtil.stepDay(dates,
												Integer.valueOf(classes.getTicketValidityTime()));
										prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
										prizeTicket.setUserId(Integer.valueOf(payRecord.getUserId()));
										prizeTicket.setClassesId(classes.getClassesId());
										prizeTicketDao.seavePrizeTicket(prizeTicket);
									}

									Box sumNumber = boxDao.getboxByBoxId(Integer.valueOf(boxIds[j]));

									// if (peizeBag != null) {
									// peizeBag.setNumber(peizeBag.getNumber() +
									// 1);
									// prizeBagDao.updatePrizeBagNumber(peizeBag);
									// } else {
									PrizeBag peizeBag = new PrizeBag();
									peizeBag.setBoxId(Integer.valueOf(boxIds[j]));
									peizeBag.setUserId(payRecord.getUserId());
									peizeBag.setOrderNumber(payRecord.getOrderNumber());
									peizeBag.setNumber(1);
									prizeBagDao.savePrizeBag(peizeBag);

									Box nowBox = boxDao.getboxByBoxId(Integer.valueOf(boxIds[j]));
									// 修改boxes状态
									int sum = boxDao.boxesSumboxNow(nowBox.getBoxesId());
									if (sum == 0) {
										Boxes boxess = new Boxes();
										boxess.setBoxesId(sumNumber.getBoxesId());
										boxess.setState(1);
										boxesDao.updateBoxesState(boxess);

										// 修改classes状态
										Boxes boxs = boxesDao.getBoxes(sumNumber.getBoxesId());
										int countBoxes = boxesDao.countBoxes(boxs.getClassesId());
										if (countBoxes == 0) {
											Classes classess = new Classes();
											classess.setSellOut(1);
											classess.setClassesId(boxess.getClassesId());
											classesDao.updateState(classess);
										}

									}

									Order order = new Order();
									order.setMoney(payRecord.getMoney());
									order.setOrderNumber(payRecord.getOrderNumber());
									order.setUserId(payRecord.getUserId());
									orderDao.saveOrder(order);
								}

								Boxes boxes = boxesDao.getBoxesById(thisboxid);
								Classes classes = classesDao.getClassesById(Integer.valueOf(boxes.getClassesId()));

								if (payRecord.getIsPrizeCoin() == 1) {
									// 扣除赏币
									User user = new User();
									user.setUserId(payRecord.getUserId());
									user.setPrizeCoin(payRecord.getPrizeCoin());
									userDao.updateaUserPrizeCoin(user);
									// 喜币消费记录
									PrizeCoinLog PrizeCoinLog = new PrizeCoinLog();
									PrizeCoinLog.setClassesId(classes.getClassesId());
									PrizeCoinLog.setNumber(payRecord.getPrizeCoins());
									PrizeCoinLog.setUserId(payRecord.getUserId());
									PrizeCoinLog.setOrderNumber(payRecord.getOrderNumber());
									prizeCoinLogDao.savePrizeCoinLog(PrizeCoinLog);
								}

								List<GiveBox> giveBoxList = giveBoxDao
										.getGiveBoxByOrderNumber(payRecord.getOrderNumber(), 0);
								if (giveBoxList.size() > 0) {
									for (GiveBox giveBox : giveBoxList) {
										Box boxByFrist = boxDao.getboxByBoxId(giveBox.getBoxId());
										if (boxByFrist.getBoxNowSum() != 0) {
											boxDao.updateBoxFristNowNumber(giveBox.getBoxId());
											// 随机一名购买过此盲盒的用户赠送first卡
											List<PrizeBag> PrizeBagUserId = prizeBagDao
													.getPrizeBagUser(boxByFrist.getBoxesId());
											Random random = new Random();
											int userId = 0;
											if (PrizeBagUserId.size() > 0) {
												int winNumbers = random.nextInt(PrizeBagUserId.size());
												userId = PrizeBagUserId.get(winNumbers).getUserId();
											} else {
												userId = payRecord.getUserId();
											}
											// 新增赏袋
											String outtradeno = WXPayUtil.getOrderId();// 生成订单号

											PrizeBag seaveFristPrizeBag = new PrizeBag();
											seaveFristPrizeBag.setBoxId(giveBox.getBoxId());
											seaveFristPrizeBag.setUserId(userId);
											seaveFristPrizeBag.setOrderNumber(outtradeno);
											seaveFristPrizeBag.setNumber(1);
											prizeBagDao.savePrizeBag(seaveFristPrizeBag);

											// 获奖记录
											PrizeLog prizeLog = new PrizeLog();
											prizeLog.setUserId(userId);
											prizeLog.setBoxId(giveBox.getBoxId());
											prizeLogDao.savePrizeLog(prizeLog);
											// 新增订单
											Order order = new Order();
											order.setMoney(new BigDecimal(0));
											order.setOrderNumber(outtradeno);
											order.setUserId(userId);
											orderDao.saveOrder(order);

											// 随机购买用户赠送赏票
											if (classes.getIsPrizeTicket() == 1) {
												PrizeTicket prizeTicket = new PrizeTicket();

												Date dates = new Date();
												Date newDate = DateUtil.stepDay(dates,
														Integer.valueOf(classes.getTicketValidityTime()));
												prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
												prizeTicket.setUserId(Integer.valueOf(userId));
												prizeTicket.setClassesId(classes.getClassesId());
												prizeTicketDao.seavePrizeTicket(prizeTicket);
											}

										}
									}
								}

								List<GiveBox> wgiveBoxList = giveBoxDao
										.getGiveBoxByOrderNumber(payRecord.getOrderNumber(), 12);
								if (wgiveBoxList.size() > 0) {
									for (GiveBox wgiveBox : wgiveBoxList) {
										Box boxByW = boxDao.getboxByBoxId(wgiveBox.getBoxId());
										if (boxByW.getBoxNowSum() != 0) {
											boxDao.updateBoxFristNowNumber(wgiveBox.getBoxId());
											// 随机一名购买过此盲盒的用户赠送W卡
											List<PrizeBag> PrizeBagUserId = prizeBagDao
													.getPrizeBagUser(boxByW.getBoxesId());
											Random random = new Random();
											int userId = 0;
											if (PrizeBagUserId.size() > 0) {
												int winNumbers = random.nextInt(PrizeBagUserId.size());
												userId = PrizeBagUserId.get(winNumbers).getUserId();
											} else {
												userId = payRecord.getUserId();
											}
											// Frist新增赏袋
											String outtradeno = WXPayUtil.getOrderId();// 生成订单号
											PrizeBag seaveFristPrizeBag = new PrizeBag();
											seaveFristPrizeBag.setBoxId(wgiveBox.getBoxId());
											seaveFristPrizeBag.setUserId(userId);
											seaveFristPrizeBag.setOrderNumber(outtradeno);
											seaveFristPrizeBag.setNumber(1);
											prizeBagDao.savePrizeBag(seaveFristPrizeBag);

											// 获奖记录
											PrizeLog prizeLog = new PrizeLog();
											prizeLog.setUserId(userId);
											prizeLog.setBoxId(wgiveBox.getBoxId());
											prizeLogDao.savePrizeLog(prizeLog);
											// 新增订单
											Order order = new Order();
											order.setMoney(new BigDecimal(0));
											order.setOrderNumber(outtradeno);
											order.setUserId(userId);
											orderDao.saveOrder(order);

											// 随机购买用户赠送赏票
											if (classes.getIsPrizeTicket() == 1) {
												PrizeTicket prizeTicket = new PrizeTicket();

												Date dates = new Date();
												Date newDate = DateUtil.stepDay(dates,
														Integer.valueOf(classes.getTicketValidityTime()));
												prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
												prizeTicket.setUserId(Integer.valueOf(userId));
												prizeTicket.setClassesId(classes.getClassesId());
												prizeTicketDao.seavePrizeTicket(prizeTicket);
											}
										}
									}
								}
							}
						}

						jsonUser.setCodeEnum(CodeEnum.SUCCESS);
					} else {
						jsonUser.setCodeEnum(CodeEnum.ERROR);
						jsonUser.setMsg(resData.get("err_code_des"));
						return jsonUser;
					}
				} else {
					jsonUser.setCodeEnum(CodeEnum.ERROR);
					jsonUser.setMsg(resData.get("return_msg"));
					return jsonUser;
				}
			}
			LOGGER.error("支付成功回调方法执行结果为:" + jsonUser);

		} catch (Exception e) {
			jsonUser.setCodeEnum(CodeEnum.ERROR);
			e.printStackTrace();
			LOGGER.error("支付成功回调方法执行结果为:" + jsonUser);

		}
		return jsonUser;
	}

	@Override
	public JsonData getJscode2session(Map<String, String> param) throws Exception {
		LOGGER.error("开始调用login接口");
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		JsonData jsonData = new JsonData();
		try {
			String usercode = maps.get("code").toString();
			String inviteId = maps.get("inviteId").toString();
			String ticketId = maps.get("ticketId").toString();
			String url = "";
			// 微信的接口
			url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + CmsConstants.WEIXIN_MINI_APPID + "&secret="
					+ CmsConstants.WEIXIN_MINI_SECRET + "&js_code=" + usercode + "&grant_type=authorization_code";
			// 进行网络请求,访问url接口
			HttpClient httpClient = HttpClientBuilder.create().build();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			String userinfoStr = EntityUtils.toString(httpEntity, "utf-8");
			net.sf.json.JSONObject jsonResp = net.sf.json.JSONObject.fromObject(userinfoStr);
			LOGGER.error("jsonresp:" + jsonResp.toString());
			// 根据返回值进行后续操作
			if (jsonResp != null && !jsonResp.equals("") && jsonResp.get("openid") != null) {

				User user = userDao.getUserByOpenId(jsonResp.get("openid").toString());
				if (user != null) {
					user.setSessionKey(jsonResp.get("session_key").toString());
					userDao.updateSessionKey(user);
					String token = TokenUse.sign(user.getPhone(), user.getUserId());
					if (token != null) {
						user.setToken(token);
					}
				} else {
					User users = userDao.getUserByOpenId(jsonResp.get("openid").toString());

					if (users == null) {
						user = new User();
						user.setOpenId(jsonResp.get("openid").toString());
						user.setSessionKey(jsonResp.get("session_key").toString());
						userDao.saveUser(user);
						String token = TokenUse.sign(user.getOpenId(), user.getUserId());
						if (token != null) {
							user.setToken(token);
						}
						
					
					}
				}
				List<PrizeTicket> prizeTicket = prizeTicketDao.getPrizeTicketByUser(user.getUserId());
				int size = prizeTicket.size();
				user.setPrizeTicketSize(size);
				
				int state = 0;
				// 通过好友分享商票打开赠送一张商票
				if (!StringUtil.isEmpty(inviteId) && !StringUtil.isEmpty(ticketId)
						&& Integer.valueOf(inviteId) != user.getUserId()) {
					if (!StringUtil.isEmpty(ticketId)) {
						List<GetTicketLog> getTicket = getTicketLogDao
								.GteTicketLogByTicketId(Integer.valueOf(ticketId));
						List<GetTicketLog> getUser = getTicketLogDao.GteTicketLogByUserId(user.getUserId());
						List<GetTicketLog> getInvite = getTicketLogDao.GteTicketLogByInviteId(user.getUserId(),
								Integer.valueOf(inviteId));
						// 判断赏票是否被抽
						if (getTicket.size() == 0 && getUser.size() <= 10 && getInvite.size() == 0) {
							GetTicketLog getTicketLog = new GetTicketLog();
							getTicketLog.setTicketId(Integer.valueOf(ticketId));
							getTicketLog.setUserId(user.getUserId());
							getTicketLog.setInviteId(Integer.valueOf(inviteId));
							getTicketLogDao.seaveGetTicketLog(getTicketLog);
							PrizeTicket getState = prizeTicketDao.getPrizeTicketById(Integer.valueOf(ticketId));
							if (Integer.valueOf(getState.getState()) == 0) {
								PrizeTicket prizeTickets = new PrizeTicket();
								SysParam sysParam = sysParamDao
										.findSysParamByKey(SysParamEnum.SYSVALIDITYTIME.getName());
								Date dates = new Date();
								Date newDate = DateUtil.stepDay(dates, Integer.valueOf(sysParam.getValue()));
								prizeTickets.setInviteId(Integer.valueOf(inviteId));
								prizeTickets.setUserId(Integer.valueOf(user.getUserId()));
								prizeTickets.setValidTime(new Timestamp(newDate.getTime()));
								PrizeTicket getClassesId = prizeTicketDao
										.getPrizeTicketById(Integer.valueOf(ticketId));
								prizeTickets.setClassesId(getClassesId.getClassesId());
								prizeTicketDao.savePrizeTicketByInvite(prizeTickets);
								// 分享人的商票状态改为可撕开
								prizeTickets.setTicketId(Integer.valueOf(ticketId));
								prizeTickets.setValidTime(new Timestamp(newDate.getTime()));
								prizeTicketDao.updatePrizeTicketStateByTicketId(prizeTickets);
							}
						} else {
							if (getTicket.size() != 0) {
								state = 1;
							} else if (getUser.size() > 10) {
								state = 2;
							} else if (getInvite.size() != 0) {
								state = 3;
							}
						}
					}
				}
				if (state == 1) {
					jsonData.setCodeEnum(CodeEnum.SUCCESS);
					jsonData.setMsg("该赏票已被领取");
				} else if (state == 2) {
					jsonData.setCodeEnum(CodeEnum.SUCCESS);
					jsonData.setMsg("该用户赠送赏票已到上限");
				} else if (state == 3) {
					jsonData.setCodeEnum(CodeEnum.SUCCESS);
					jsonData.setMsg("已领取过该推荐人的赏票");
				}else{
					jsonData.setCodeEnum(CodeEnum.SUCCESS);
				}
				jsonData.setData(user);
				return jsonData;
			} else {
				jsonData.setCodeEnum(CodeEnum.ERROR);
			}
		} catch (Exception e) {
			jsonData.setCodeEnum(CodeEnum.ERROR);
			LOGGER.error("登录错误");
			e.printStackTrace();
		}
		return jsonData;
	}

	// 授权获取用户手机号
	@Override
	public JsonData getPersonalInformation(Map<String, String> param) {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String token = param.get("token");
		String encryptedDataStr = maps.get("encryptedDataStr").toString();
		String ivStr = maps.get("ivStr").toString();
		try {
			User oldUser = userDao.getUserById(TokenUse.getUserID(token));
			String entity = WechatDecryptDataUtil.decryptData(encryptedDataStr, oldUser.getSessionKey(), ivStr);
			net.sf.json.JSONObject jsonResp = net.sf.json.JSONObject.fromObject(entity);
			User user = new User();
			user.setUserId(TokenUse.getUserID(token));
			user.setPhone(jsonResp.get("phoneNumber").toString());
			userDao.updateUserPhone(user);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
			jsonData.setData(user.getPhone());
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	// 获取用户信息
	@Override
	public JsonData updateUserInfo(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		try {
			Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
			String token = param.get("token");
			String avatarUrl = maps.get("avatarUrl").toString();
			String nickName = maps.get("nickName").toString();
			User user = userDao.getUserById(TokenUse.getUserID(token));
			user.setHead(avatarUrl);
			user.setUserName(nickName);
			user.setUserId(TokenUse.getUserID(token));
			userDao.updateUserInfo(user);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
			jsonData.setData(user);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getSysMessage(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String type = maps.get("type").toString();
		try {
			SysMessage sysMessage = sysMessageDao.getSysMessage(Integer.valueOf(type));
			jsonData.setData(sysMessage);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData moneybuyBox(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		JsonData jsonData = new JsonData();

		String type = maps.get("type").toString();// 抽奖类型 1抽一发 2抽三发 3抽五发 4为全收
		String boxesId = maps.get("boxesId").toString();
		String isPrizeCoin = maps.get("isPrizeCoin").toString();// 是否使用赏币0为不用
		String token = param.get("token");
		String outtradeno = WXPayUtil.getOrderId();// 生成订单号
		User users = userDao.getUserById(TokenUse.getUserID(token));
		BigDecimal prizeCoins = users.getPrizeCoin();
		try {
			Boxes boxes = boxesDao.getBoxes(Integer.valueOf(boxesId));
			Classes classes = classesDao.getClassesById(Integer.valueOf(boxes.getClassesId()));
			BigDecimal price = classes.getPrice();
			int howDraw = 0;

			int ruleId = classes.getRuleId();
			StringBuffer boxIds = new StringBuffer();
			int boxCount = boxDao.boxesSumboxNow(Integer.valueOf(boxesId));
			if (Integer.valueOf(type) == 1) { // 1抽一发
				howDraw = 1;
			}
			if (Integer.valueOf(type) == 2) {// 1抽三发
				howDraw = 3;
			}
			if (Integer.valueOf(type) == 3) {
				howDraw = 5;
			}
			if (Integer.valueOf(type) == 4) {
				int count = boxDao.boxesSumboxNow(boxes.getBoxesId());
				howDraw = count;
			}
			if (boxCount == 0 || howDraw > boxCount) {
				jsonData.setCodeEnum(CodeEnum.BOXERROR);
				return jsonData;
			}
			BigDecimal howDrawCount = new BigDecimal(howDraw);// 来几发
			BigDecimal money = price.multiply(howDrawCount);
			BigDecimal makePrizeCoin = money;
			if (Integer.valueOf(isPrizeCoin) == 1) {// 是否使用赏币
				if (money.compareTo(prizeCoins) > -1) { // 金额大于等于用户赏币
					money = money.subtract(prizeCoins);
					users.setPrizeCoin(new BigDecimal(0));
				} else {
					BigDecimal coins = prizeCoins.subtract(money);
					users.setPrizeCoin(coins);
					money = new BigDecimal(0);
				}
			}
			if (users.getAccountMoney().compareTo(money) > -1) {
				users.setAccountMoney(users.getAccountMoney().subtract(money));
			} else {
				jsonData.setCodeEnum(CodeEnum.BALANCE_NOT_ENOUGH);
				return jsonData;
			}
			List<Box> box = boxDao.getLastBoxAll(Integer.valueOf(boxesId));
			int sumCount = boxDao.boxesSumboxNow(Integer.valueOf(boxesId));
			int SumCountAll = boxDao.boxesSumbox(Integer.valueOf(boxesId));
			int residueCount = SumCountAll - sumCount;
			if (ruleId == 1) {
				System.out.println("-----------------------------------------" + howDraw);
				wai: for (int i = 0; i < howDraw; i++) {
					Random random = new Random();
					List<Integer> boxIdList = new ArrayList<Integer>();
					for (Box boxs : box) {
						for (int j = 0; j < boxs.getXnBoxNowSum(); j++) {
							boxIdList.add(boxs.getBoxId());
						}
					}
					int winNumber = random.nextInt(boxIdList.size());
					boolean ifTrue = RedisUtil.exists("manghe" + boxIdList.get(winNumber));
					if (ifTrue) {
						String countNumber = RedisUtil.get("manghe" + boxIdList.get(winNumber));
						int nowSum = 0;
						nei: for (int p = 0; p < box.size(); p++) {
							if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
								nowSum = box.get(p).getBoxNowSum() - Integer.valueOf(countNumber);
								box.get(p).setXnBoxNowSum(box.get(p).getXnBoxNowSum() - 1);
								if (nowSum <= 0) {
									box.remove(p);
									if (box.size() <= 0) {
										jsonData.setCodeEnum(CodeEnum.BOXERROR);
										return jsonData;
									} else {
										i--;
										continue wai;
									}
								} else {
									// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
									// - 1);
									if (boxIds.length() == 0) {
										boxIds = new StringBuffer();
										boxIds.append(boxIdList.get(winNumber));
									} else {
										boxIds.append("," + boxIdList.get(winNumber));
									}
									RedisUtil.incr("manghe" + boxIdList.get(winNumber));
									if (String.valueOf(RedisUtil.ttl("manghe" + boxIdList.get(winNumber)))
											.equals("-1")) {
										RedisUtil.expire("manghe" + boxIdList.get(winNumber), 5);
									}
								}
								break nei;
							}
						}
					} else {
						// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
						// - 1);
						if (boxIds.length() == 0) {
							boxIds = new StringBuffer();
							boxIds.append(boxIdList.get(winNumber));
						} else {
							boxIds.append("," + boxIdList.get(winNumber));
						}
						RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1", 5);
					}
				}
			} else if (ruleId == 2) {
				wai: for (int i = 0; i < howDraw; i++) {
					Random random = new Random();
					List<Integer> boxIdList = new ArrayList<Integer>();
					for (Box boxs : box) {
						for (int j = 0; j < boxs.getXnBoxNowSum(); j++) {
							boxIdList.add(boxs.getBoxId());
						}
					}
					int winNumber = random.nextInt(boxIdList.size());
					boolean ifTrue = RedisUtil.exists("manghe" + boxIdList.get(winNumber));
					if (ifTrue) {
						String countNumber = RedisUtil.get("manghe" + boxIdList.get(winNumber));
						int nowSum = 0;
						nei: for (int p = 0; p < box.size(); p++) {
							if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
								nowSum = box.get(p).getBoxNowSum() - Integer.valueOf(countNumber);
								box.get(p).setXnBoxNowSum(box.get(p).getXnBoxNowSum() - 1);
								if (nowSum <= 0) {
									box.remove(p);
									if (box.size() <= 0) {
										jsonData.setCodeEnum(CodeEnum.BOXERROR);
										return jsonData;
									} else {
										i--;
										continue wai;
									}
								} else {
									// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
									// - 1);
									if (boxIds.length() == 0) {
										boxIds = new StringBuffer();
										boxIds.append(boxIdList.get(winNumber));
									} else {
										boxIds.append("," + boxIdList.get(winNumber));
									}
									RedisUtil.incr("manghe" + boxIdList.get(winNumber));
									if (String.valueOf(RedisUtil.ttl("manghe" + boxIdList.get(winNumber)))
											.equals("-1")) {
										RedisUtil.expire("manghe" + boxIdList.get(winNumber), 5);
									}
									residueCount = residueCount + 1;
								}
								break nei;
							}
						}
					} else {
						// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
						// - 1);
						if (boxIds.length() == 0) {
							boxIds = new StringBuffer();
							boxIds.append(boxIdList.get(winNumber));
						} else {
							boxIds.append("," + boxIdList.get(winNumber));
						}
						RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1", 5);
						residueCount = residueCount + 1;
					}
					// 赠送last赏
					if (SumCountAll == residueCount) {
						Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
						boxIds.append("," + lastBox.getBoxId());
						// 赠送商票
						if (classes.getIsPrizeTicket() == 1) {
							PrizeTicket prizeTicket = new PrizeTicket();
							Date dates = new Date();
							Date newDate = DateUtil.stepDay(dates, Integer.valueOf(classes.getTicketValidityTime()));
							prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
							prizeTicket.setUserId(Integer.valueOf(users.getUserId()));
							prizeTicket.setClassesId(classes.getClassesId());
							prizeTicketDao.seavePrizeTicket(prizeTicket);
						}

					}
				}
			} else if (ruleId == 3) {
				GiveBox giveBox = new GiveBox();
				wai: for (int i = 0; i < howDraw; i++) {
					Random random = new Random();
					List<Integer> boxIdList = new ArrayList<Integer>();
					for (Box boxs : box) {
						for (int j = 0; j < boxs.getXnBoxNowSum(); j++) {
							boxIdList.add(boxs.getBoxId());
						}
					}
					int winNumber = random.nextInt(boxIdList.size());
					boolean ifTrue = RedisUtil.exists("manghe" + boxIdList.get(winNumber));
					if (ifTrue) {
						String countNumber = RedisUtil.get("manghe" + boxIdList.get(winNumber));
						int nowSum = 0;
						nei: for (int p = 0; p < box.size(); p++) {
							if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
								nowSum = box.get(p).getBoxNowSum() - Integer.valueOf(countNumber);
								box.get(p).setXnBoxNowSum(box.get(p).getXnBoxNowSum() - 1);
								if (nowSum <= 0) {
									box.remove(p);
									if (box.size() <= 0) {
										jsonData.setCodeEnum(CodeEnum.BOXERROR);
										return jsonData;
									} else {
										i--;
										continue wai;
									}
								} else {
									// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
									// - 1);
									if (boxIds.length() == 0) {
										boxIds = new StringBuffer();
										boxIds.append(boxIdList.get(winNumber));
									} else {
										boxIds.append("," + boxIdList.get(winNumber));
									}
									RedisUtil.incr("manghe" + boxIdList.get(winNumber));
									if (String.valueOf(RedisUtil.ttl("manghe" + boxIdList.get(winNumber)))
											.equals("-1")) {
										RedisUtil.expire("manghe" + boxIdList.get(winNumber), 5);
									}
									residueCount = residueCount + 1;
								}
								break nei;
							}
						}
					} else {
						// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
						// - 1);
						if (boxIds.length() == 0) {
							boxIds = new StringBuffer();
							boxIds.append(boxIdList.get(winNumber));
						} else {
							boxIds.append("," + boxIdList.get(winNumber));
						}
						RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1", 5);
						residueCount = residueCount + 1;
					}
					// 赠送Frist赏
					int ceaseCount = (int) Math.ceil(Double.valueOf(SumCountAll) / 2.0);

					if (residueCount == ceaseCount) {
						Box boxFrist = boxDao.getboxByFrist(Integer.valueOf(boxesId));
						giveBox.setBoxId(boxFrist.getBoxId());
						giveBox.setUserId(0);
						giveBox.setBoxLevel(Integer.valueOf(boxFrist.getBoxLevel()));
						giveBox.setOrderNumber(outtradeno);
						giveBoxDao.saveGiveBoxByBoxId(giveBox);
						// 赠送last赏
					} else if (SumCountAll == residueCount) {
						Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
						boxIds.append("," + lastBox.getBoxId());
						// 赠送商票
						if (classes.getIsPrizeTicket() == 1) {
							PrizeTicket prizeTicket = new PrizeTicket();
							Date dates = new Date();
							Date newDate = DateUtil.stepDay(dates, Integer.valueOf(classes.getTicketValidityTime()));
							prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
							prizeTicket.setUserId(Integer.valueOf(users.getUserId()));
							prizeTicket.setClassesId(classes.getClassesId());
							prizeTicketDao.seavePrizeTicket(prizeTicket);
						}
					}
				}
			} else if (ruleId == 4) {
				GiveBox giveBox = new GiveBox();
				GiveBox giveWLsetBox = new GiveBox();
				wai: for (int i = 0; i < howDraw; i++) {
					Random random = new Random();
					List<Integer> boxIdList = new ArrayList<Integer>();
					for (Box boxs : box) {
						for (int j = 0; j < boxs.getXnBoxNowSum(); j++) {
							boxIdList.add(boxs.getBoxId());
						}
					}
					int winNumber = random.nextInt(boxIdList.size());
					boolean ifTrue = RedisUtil.exists("manghe" + boxIdList.get(winNumber));
					if (ifTrue) {
						String countNumber = RedisUtil.get("manghe" + boxIdList.get(winNumber));
						int nowSum = 0;
						nei: for (int p = 0; p < box.size(); p++) {
							if (box.get(p).getBoxId() == boxIdList.get(winNumber)) {
								nowSum = box.get(p).getBoxNowSum() - Integer.valueOf(countNumber);
								box.get(p).setXnBoxNowSum(box.get(p).getXnBoxNowSum() - 1);
								if (nowSum <= 0) {
									box.remove(p);
									if (box.size() <= 0) {
										jsonData.setCodeEnum(CodeEnum.BOXERROR);
										return jsonData;
									} else {
										i--;
										continue wai;
									}
								} else {
									// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
									// - 1);
									if (boxIds.length() == 0) {
										boxIds = new StringBuffer();
										boxIds.append(boxIdList.get(winNumber));
									} else {
										boxIds.append("," + boxIdList.get(winNumber));
									}
									RedisUtil.incr("manghe" + boxIdList.get(winNumber));
									if (String.valueOf(RedisUtil.ttl("manghe" + boxIdList.get(winNumber)))
											.equals("-1")) {
										RedisUtil.expire("manghe" + boxIdList.get(winNumber), 5);
									}
									residueCount = residueCount + 1;
								}
								break nei;
							}
						}
					} else {
						// box.get(winNumber).setBoxNowSum(box.get(winNumber).getBoxNowSum()
						// - 1);
						if (boxIds.length() == 0) {
							boxIds = new StringBuffer();
							boxIds.append(boxIdList.get(winNumber));
						} else {
							boxIds.append("," + boxIdList.get(winNumber));
						}
						RedisUtil.setex("manghe" + boxIdList.get(winNumber), "1", 5);
						residueCount = residueCount + 1;
					}
					// 赠送frist赏
					int ceaseCount = (int) Math.ceil(Double.valueOf(SumCountAll) / 2.0);
					if (residueCount == ceaseCount) {
						Box boxFrist = boxDao.getboxByFrist(Integer.valueOf(boxesId));
						giveBox.setBoxId(boxFrist.getBoxId());
						giveBox.setUserId(0);
						giveBox.setBoxLevel(Integer.valueOf(boxFrist.getBoxLevel()));
						giveBox.setOrderNumber(outtradeno);
						giveBoxDao.saveGiveBoxByBoxId(giveBox);
						// 赠送两张赏票

					} else if (SumCountAll == residueCount) {
						Box lastBox = boxDao.getLastBox(Integer.valueOf(boxesId));
						boxIds.append("," + lastBox.getBoxId());
						Box boxW = boxDao.getboxByW(Integer.valueOf(boxesId));
						giveWLsetBox.setBoxId(boxW.getBoxId());
						giveWLsetBox.setUserId(0);
						giveWLsetBox.setBoxLevel(Integer.valueOf(boxW.getBoxLevel()));
						giveWLsetBox.setOrderNumber(outtradeno);
						giveBoxDao.saveGiveBoxByBoxId(giveWLsetBox);
					}
				}
			}
			String[] cardNumber = String.valueOf(boxIds).split(",");
			if (howDraw > cardNumber.length) {
				jsonData.setCodeEnum(CodeEnum.BOXERROR);
				return jsonData;
			}
			PayRecord payRecord = new PayRecord();

			payRecord.setUserId(users.getUserId());
			payRecord.setMoney(money);
			payRecord.setOrderNumber(outtradeno);
			payRecord.setBoxId(String.valueOf(boxIds));
			payRecord.setState(1);
			payRecord.setPrizeCoins(prizeCoins);
			payRecordDao.savePayRecord(payRecord);

			String[] getboxIds = payRecord.getBoxId().split(",");

			for (int j = 0; j < getboxIds.length; j++) {

				// 获奖记录
				PrizeLog prizeLog = new PrizeLog();
				prizeLog.setUserId(payRecord.getUserId());
				prizeLog.setBoxId(Integer.valueOf(getboxIds[j]));
				prizeLogDao.savePrizeLog(prizeLog);

				// 用户赠送赏票
				if (classes.getIsPrizeTicket() == 1) {
					PrizeTicket prizeTicket = new PrizeTicket();

					Date dates = new Date();
					Date newDate = DateUtil.stepDay(dates, Integer.valueOf(classes.getTicketValidityTime()));
					prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
					prizeTicket.setUserId(Integer.valueOf(payRecord.getUserId()));
					prizeTicket.setClassesId(classes.getClassesId());
					prizeTicketDao.seavePrizeTicket(prizeTicket);
				}

				if (getboxIds[j] != null && !getboxIds[j].equals("")) {
					Box sumNumber = boxDao.getboxByBoxId(Integer.valueOf(getboxIds[j]));
					// 减库存
					sumNumber.setBoxNowSum(sumNumber.getBoxNowSum() - 1);
					sumNumber.setBoxId(Integer.valueOf(getboxIds[j]));
					boxDao.updateBoxNowSum(sumNumber);

					// if (peizeBag != null) {
					// peizeBag.setNumber(peizeBag.getNumber() + 1);
					// prizeBagDao.updatePrizeBagNumber(peizeBag);
					// } else {
					PrizeBag peizeBag = new PrizeBag();
					peizeBag.setBoxId(Integer.valueOf(getboxIds[j]));
					peizeBag.setUserId(payRecord.getUserId());
					peizeBag.setOrderNumber(payRecord.getOrderNumber());
					peizeBag.setNumber(1);
					prizeBagDao.savePrizeBag(peizeBag);

					Box nowBox = boxDao.getboxByBoxId(Integer.valueOf(getboxIds[j]));
					// 修改boxes状态
					int sum = boxDao.boxesSumboxNow(nowBox.getBoxesId());
					if (sum == 0) {
						Boxes getsboxes = new Boxes();
						getsboxes.setBoxesId(sumNumber.getBoxesId());
						getsboxes.setState(1);
						boxesDao.updateBoxesState(getsboxes);

						// 修改classes状态
						Boxes boxess = boxesDao.getBoxes(sumNumber.getBoxesId());
						int countBoxes = boxesDao.countBoxes(boxess.getClassesId());
						if (countBoxes == 0) {
							Classes newClasses = new Classes();
							newClasses.setSellOut(1);
							newClasses.setClassesId(boxess.getClassesId());
							classesDao.updateState(newClasses);
						}

					}
				}
			}

			if (Integer.valueOf(isPrizeCoin) == 1) {
				// 喜币消费记录
				PrizeCoinLog PrizeCoinLog = new PrizeCoinLog();
				PrizeCoinLog.setClassesId(classes.getClassesId());
				PrizeCoinLog.setNumber(makePrizeCoin);
				PrizeCoinLog.setUserId(payRecord.getUserId());
				PrizeCoinLog.setOrderNumber(payRecord.getOrderNumber());
				prizeCoinLogDao.savePrizeCoinLog(PrizeCoinLog);
			}

			Order order = new Order();
			order.setMoney(payRecord.getMoney());
			order.setOrderNumber(payRecord.getOrderNumber());
			order.setUserId(payRecord.getUserId());
			orderDao.saveOrder(order);
			userDao.updateaUserAccountMoney(users);
			List<GiveBox> giveBoxList = giveBoxDao.getGiveBoxByOrderNumber(payRecord.getOrderNumber(), 0);
			if (giveBoxList.size() > 0) {
				for (GiveBox giveBox : giveBoxList) {
					Box boxByFrist = boxDao.getboxByBoxId(giveBox.getBoxId());
					if (boxByFrist.getBoxNowSum() != 0) {
						// // 随机一名购买过此盲盒的用户赠送first卡
						List<PrizeBag> PrizeBagUserId = prizeBagDao.getPrizeBagUser(boxByFrist.getBoxesId());
						Random random = new Random();
						int userId = 0;
						if (PrizeBagUserId.size() > 0) {
							int winNumbers = random.nextInt(PrizeBagUserId.size());
							userId = PrizeBagUserId.get(winNumbers).getUserId();
						} else {
							userId = TokenUse.getUserID(token);
						}
						// 新增赏袋
						String newouttradeno = WXPayUtil.getOrderId();// 生成订单号

						PrizeBag seaveFristPrizeBag = new PrizeBag();
						seaveFristPrizeBag.setBoxId(giveBox.getBoxId());
						seaveFristPrizeBag.setUserId(userId);
						seaveFristPrizeBag.setOrderNumber(newouttradeno);
						seaveFristPrizeBag.setNumber(1);
						prizeBagDao.savePrizeBag(seaveFristPrizeBag);
						// 获奖记录
						PrizeLog prizeLog = new PrizeLog();
						prizeLog.setUserId(userId);
						prizeLog.setBoxId(giveBox.getBoxId());
						prizeLogDao.savePrizeLog(prizeLog);
						boxDao.updateBoxFristNowNumber(giveBox.getBoxId());
						// 商票赠送
						if (classes.getIsPrizeTicket() == 1) {
							PrizeTicket prizeTicket = new PrizeTicket();
							Date dates = new Date();
							Date newDate = DateUtil.stepDay(dates, Integer.valueOf(classes.getTicketValidityTime()));
							prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
							prizeTicket.setUserId(giveBox.getUserId());
							prizeTicket.setClassesId(classes.getClassesId());
							prizeTicketDao.seavePrizeTicket(prizeTicket);
						}
						// 新增订单
						Order orders = new Order();
						orders.setMoney(new BigDecimal(0));
						orders.setOrderNumber(outtradeno);
						orders.setUserId(giveBox.getUserId());
						orderDao.saveOrder(orders);
					}
				}
			}

			List<GiveBox> wgiveBoxList = giveBoxDao.getGiveBoxByOrderNumber(payRecord.getOrderNumber(), 12);
			if (wgiveBoxList.size() > 0) {
				for (GiveBox wgiveBox : wgiveBoxList) {
					Box boxByW = boxDao.getboxByBoxId(wgiveBox.getBoxId());
					if (boxByW.getBoxNowSum() != 0) {
						// 随机一名购买过此盲盒的用户赠送W卡
						List<PrizeBag> PrizeBagUserId = prizeBagDao.getPrizeBagUser(boxByW.getBoxesId());
						Random random = new Random();
						int userId = 0;
						if (PrizeBagUserId.size() > 0) {
							int winNumbers = random.nextInt(PrizeBagUserId.size());
							userId = PrizeBagUserId.get(winNumbers).getUserId();
						} else {
							userId = TokenUse.getUserID(token);
						}
						String outtradenos = WXPayUtil.getOrderId();// 生成订单号
						PrizeBag seaveFristPrizeBag = new PrizeBag();
						seaveFristPrizeBag.setBoxId(wgiveBox.getBoxId());
						seaveFristPrizeBag.setUserId(userId);
						seaveFristPrizeBag.setOrderNumber(outtradenos);
						seaveFristPrizeBag.setNumber(1);
						prizeBagDao.savePrizeBag(seaveFristPrizeBag);

						// 获奖记录
						PrizeLog prizeLog = new PrizeLog();
						prizeLog.setUserId(userId);
						prizeLog.setBoxId(wgiveBox.getBoxId());
						prizeLogDao.savePrizeLog(prizeLog);
						boxDao.updateBoxFristNowNumber(wgiveBox.getBoxId());
						// 赠送商票
						if (classes.getIsPrizeTicket() == 1) {
							PrizeTicket prizeTicket = new PrizeTicket();
							Date dates = new Date();
							Date newDate = DateUtil.stepDay(dates, Integer.valueOf(classes.getTicketValidityTime()));
							prizeTicket.setValidTime(new Timestamp(newDate.getTime()));
							prizeTicket.setUserId(Integer.valueOf(wgiveBox.getUserId()));
							prizeTicket.setClassesId(classes.getClassesId());
							prizeTicketDao.seavePrizeTicket(prizeTicket);
						}
						// 新增订单
						Order ordera = new Order();
						ordera.setMoney(new BigDecimal(0));
						ordera.setOrderNumber(outtradeno);
						ordera.setUserId(wgiveBox.getUserId());
						orderDao.saveOrder(ordera);
					}
				}

			}
			// 返回抽奖信息
			String[] boxIdsa = String.valueOf(boxIds).split(",");
			Classes classesId = classesDao.getClassesById(boxes.getClassesId());
			Map<String, Object> map = new HashMap<String, Object>();

			List<Box> boxList = new ArrayList<Box>();
			for (String boxIdss : boxIdsa) {
				Box boxid = boxDao.getboxByBoxId(Integer.valueOf(boxIdss));

				// for (Box boxs : boxList) {
				// if (boxid.getBoxId() == boxs.getBoxId()) {
				// boxs.setWinNumber(boxs.getWinNumber() + 1);
				// continue all;
				// }
				// }
				// boxid.setWinNumber(1);
				boxList.add(boxid);
			}
			map.put("isPrizeTicket", classesId.getIsPrizeTicket());
			map.put("boxList", boxList);
			jsonData.setData(map);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
			return jsonData;

		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData PayMoney(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		JsonData jsonData = new JsonData();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String money = maps.get("money").toString();// 充值金额
		String token = param.get("token");
		String outtradeno = WXPayUtil.getOrderId();// 生成订单号
		User users = userDao.getUserById(TokenUse.getUserID(token));
		Map<String, String> map = new HashMap<String, String>();
		map.put("trade_type", "JSAPI");// 交易類型
		map.put("openid", users.getOpenId());// 扫码人的openid(公众号支付必传)
		map.put("appid", CmsConstants.WEIXIN_MINI_APPID);// 公眾賬號id
		map.put("mch_id", CmsConstants.WEIXIN_SHOPNUMBER);// 商戶號
		map.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
		map.put("body", "11111");// 订单描述
		map.put("out_trade_no", outtradeno);// 商户订单号
		map.put("total_fee", WXPayUtil.getMoney(money + ""));// 标价金额（分为单位）
		map.put("spbill_create_ip", WXPayUtil.getIp(request));// 客户端ip
		// System.out.println("客户端ip:"+WeiXinUtil.getIp(this.getRequest()));
		map.put("notify_url", CmsConstants.WEIXIN_URL + "/blind_box_mall/security/payMoneySuccess");// 支付成功回調地址,通知url必须为外网可访问的url,不能携带参数。
		String sign = WXPayUtil.generateSignature(map, CmsConstants.WEIXIN_KEY, SignType.MD5);
		map.put("sign", sign);// 签名
		// 轉成XML
		String xml = WXPayUtil.mapToXml(map);
		// 發起post請求
		String response = HttpUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
		System.out.println("1---" + response);
		// xml 转 map
		Map<String, String> resData = WXPayUtil.xmlToMap(response);
		if (resData.get("return_code").equals("FAIL")) {
			jsonData.setCodeEnum(CodeEnum.ERROR_PAY);
			jsonData.setMsg(resData.get("return_msg"));
			return jsonData;
		} else if (resData.get("result_code").equals("FAIL")) {
			jsonData.setCodeEnum(CodeEnum.ERROR_PAY);
			jsonData.setMsg(resData.get("err_code_des"));
			return jsonData;
		}
		PayLog payLog = new PayLog();
		payLog.setUserId(users.getUserId());
		payLog.setMoney(new BigDecimal(money));
		payLog.setOrderNumber(outtradeno);
		payLogDao.savePayLog(payLog);
		Map<String, String> returnMap = new HashMap<String, String>();
		returnMap.put("appId", CmsConstants.WEIXIN_MINI_APPID);
		String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
		returnMap.put("timeStamp", timeStamp);
		returnMap.put("nonceStr", WXPayUtil.generateNonceStr());
		returnMap.put("package", "prepay_id=" + resData.get("prepay_id"));
		returnMap.put("signType", "MD5");
		String paySign = WXPayUtil.generateSignature(returnMap, CmsConstants.WEIXIN_KEY, SignType.MD5);
		System.out.println(paySign);
		returnMap.put("paySign", paySign);// 签名
		jsonData.setData(returnMap);
		jsonData.setList(outtradeno);
		jsonData.setCodeEnum(CodeEnum.SUCCESS);
		return jsonData;
	}

	@Override
	public JsonData payCallBackHandleisPayMoney(Map<String, String> param) throws Exception {
		JsonData jsonUser = new JsonData();
		String inputLine;
		String notityXml = "";
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			if (StringUtils.isEmpty(notityXml)) {
				System.out.println("支付回调xml为空");
			} else {
				// xml转map
				Map<String, String> resData = WXPayUtil.xmlToMap(notityXml);
				System.out.println(resData);
				if (resData.get("return_code").equals("SUCCESS")) {
					if (resData.get("result_code").equals("SUCCESS")) {

					}
					PayLog payLog = payLogDao.getPayLogOrderNumber(resData.get("out_trade_no").toString());
					if (payLog.getState() == 0) {
						payLog.setState(1);
						payLogDao.updatePayLogState(payLog);

						User user = userDao.getUserById(payLog.getUserId());
						user.getAccountMoney();
						user.setAccountMoney(user.getAccountMoney().add(payLog.getMoney()));
						userDao.updateaUserAccountMoney(user);
						jsonUser.setCodeEnum(CodeEnum.SUCCESS);
					} else {
						jsonUser.setCodeEnum(CodeEnum.ERROR);
						jsonUser.setMsg(resData.get("err_code_des"));
						return jsonUser;
					}
				} else {
					jsonUser.setCodeEnum(CodeEnum.ERROR);
					jsonUser.setMsg(resData.get("return_msg"));
					return jsonUser;
				}
			}
			LOGGER.error("支付成功回调方法执行结果为:" + jsonUser);

		} catch (Exception e) {
			jsonUser.setCodeEnum(CodeEnum.ERROR);
			e.printStackTrace();
			LOGGER.error("支付成功回调方法执行结果为:" + jsonUser);

		}
		return jsonUser;
	}

	@Override
	public JsonData returnPrizeBox(Map<String, String> param) throws Exception {
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());

		String outtradeno = maps.get("outtradeno").toString();
		JsonData jsonData = new JsonData();

		try {
			PayRecord payRecord = payRecordDao.getPayRecordByOrderNumber(outtradeno);
			if (payRecord.getState() == 1) {
				String[] boxIds = payRecord.getBoxId().split(",");
				Map<String, Object> map = new HashMap<String, Object>();
				List<Box> boxList = new ArrayList<Box>();

				Box box = boxDao.getboxByBoxId(Integer.valueOf(boxIds[0]));
				Boxes boxes = boxesDao.getBoxes(box.getBoxesId());
				Classes classesId = classesDao.getClassesById(boxes.getClassesId());

				for (String boxIdss : boxIds) {
					Box boxid = boxDao.getboxByBoxId(Integer.valueOf(boxIdss));
					// for (Box boxs : boxList) {
					// if (boxid.getBoxId() == boxs.getBoxId()) {
					// boxs.setWinNumber(boxs.getWinNumber() + 1);
					// continue all;
					// }
					// }
					boxList.add(boxid);
				}

				map.put("isPrizeTicket", classesId.getIsPrizeTicket());
				map.put("boxList", boxList);
				jsonData.setData(map);
				jsonData.setCodeEnum(CodeEnum.SUCCESS);
			} else {
				jsonData.setCodeEnum(CodeEnum.PAYERROR);
			}

		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getPrizeCoin(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		try {
			User user = userDao.getPrizeCoin(TokenUse.getUserID(token));

			jsonData.setData(user);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getSysNews(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");

		try {
			List<SysNews> sysNews = sysNewsDao.getSysNews();

			UnreadNews unreadNews = new UnreadNews();

			for (int i = 0; i < sysNews.size(); i++) {

				UnreadNews getunreadNews = unreadNewsDao.selectUnreadNews(Integer.valueOf(TokenUse.getUserID(token)),
						sysNews.get(i).getNewsId());
				if (getunreadNews == null) {
					unreadNews.setUserId(Integer.valueOf(TokenUse.getUserID(token)));
					unreadNews.setNewsId(Integer.valueOf(sysNews.get(i).getNewsId()));
					unreadNewsDao.saveUnreadNews(unreadNews);
				}
			}
			jsonData.setData(sysNews);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData countUnreadNews(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");

		try {
			int countUnreadNews = unreadNewsDao.countUnreadNews(Integer.valueOf(TokenUse.getUserID(token)));

			int countSysNews = sysNewsDao.countSysNews();
			jsonData.setData(countSysNews - countUnreadNews);

			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getUserCoin(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		try {
			List<UserCoin> userCoin = userCoinDao.getUserCoin(TokenUse.getUserID(token));
			jsonData.setData(userCoin);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData saveUserCoin(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		String coinNumber = param.get("coinNumber");
		UserCoin userCoin = new UserCoin();
		userCoin.setUserId(TokenUse.getUserID(token));
		userCoin.setCoinNumber(new BigDecimal(coinNumber));
		try {
			userCoinDao.saveUserCoin(userCoin);
			jsonData.setData(userCoin);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData getPrizeCoinLog(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		try {
			List<PrizeCoinLog> prizeCoinLog = prizeCoinLogDao.getPrizeCoinLog(TokenUse.getUserID(token));
			jsonData.setData(prizeCoinLog);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

	@Override
	public JsonData tuikuan(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String orderNumber = param.get("orderNumber");
		try {
			PayRecord payRecord = payRecordDao.getPayRecordByOrderNumber(orderNumber);
			Map<String, String> map = new HashMap<String, String>();
			map.put("appid", CmsConstants.WEIXIN_MINI_APPID);// 公眾賬號id
			map.put("mch_id", CmsConstants.WEIXIN_SHOPNUMBER);// 商戶號
			map.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
			map.put("out_trade_no", orderNumber);// 商户订单号
			map.put("out_refund_no", WXPayUtil.generateNonceStr() + orderNumber);// 商户订单号
			map.put("total_fee", WXPayUtil.getMoney(payRecord.getMoney() + ""));// 标价金额（分为单位）
			map.put("refund_fee", WXPayUtil.getMoney(payRecord.getMoney() + ""));
			// System.out.println("客户端ip:"+WeiXinUtil.getIp(this.getRequest()));
			// 签名算法
			String sign = WXPayUtil.generateSignature(map, CmsConstants.WEIXIN_KEY, SignType.MD5);
			map.put("sign", sign);// 签名
			// 轉成XML
			String xml = WXPayUtil.mapToXml(map);
			// 带证书的post
			String resXml = CertHttpUtil.postData("https://api.mch.weixin.qq.com/secapi/pay/refund", xml);

			jsonData.setData(resXml);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}

}
